package cn.zqy.services;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import cn.zqy.model.Library;

public class PersistentService
{
	protected final Logger log = Logger.getLogger(this.getClass().getName());
	
	public void persistent(Object object)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			pm.makePersistent(object);
			
		}
		catch(Exception e)
		{
			log.severe(e.toString());
		}
		finally
		{
			pm.close();
		}
	}
	
	public void update(Object object)
	{
		//if detachable="true"
		//@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
		persistent(object);
		//else
		//TODO
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Object> retrieveAll(Class cls,String orderCondition)
	{
		ArrayList<Object> objectList=new ArrayList<Object>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			Query query=pm.newQuery(cls);
			if(orderCondition.length()>0)
			{
				query.setOrdering(orderCondition);
			}
			for(Object object:(List<Object>)query.execute())
			{
				objectList.add(object);
			}
		}
		catch(Exception e)
		{
			log.severe(e.toString());
		}
		finally
		{
			pm.close();
		}
		return objectList;
	}
	
	public void delete(Class<?> cls,Object objectId)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction trans=pm.currentTransaction();
		try
		{	
			trans.begin();
			pm.deletePersistent(pm.getObjectById(cls,objectId));
			trans.commit();
		}
		catch(Exception e)
		{
			log.severe(e.toString());
		}
		finally
		{
			if(trans.isActive())
			{
				trans.rollback();
			}
			pm.close();
		}
	}
}
